import openpyxl
from config.config import EXCEL_FILE


def read_excel():

    workbook = openpyxl.load_workbook(EXCEL_FILE)

    data = []

    # 先把所有用例数据读出来, 再进行筛选, 合格的用例才添加到 data 中
    all_cases = []
    # 定义当前用例数据, 组织处理每一条用例数据的问题
    current_case = None

    # worksheet = workbook["Sheet1"] 这里加个循环就行了
    for worksheet in workbook.worksheets:

        keys = [cell.value for cell in worksheet[2]]
        for row in worksheet.iter_rows(min_row=3, values_only=True):
            dict_data = dict(zip(keys, row))

            # 只要id不为None, 代表这是一条新用例
            if dict_data["id"] is not None:

                # 组织用例的过程
                current_case = {
                    "id": dict_data["id"],
                    "feature": dict_data["feature"],
                    "story": dict_data["story"],
                    "title": dict_data["title"],
                    "steps": [{
                        "step_num": dict_data["step_num"],
                        "step_name": dict_data["step_name"],
                        "keyword": dict_data["keyword"],
                        "by": dict_data["by"],
                        "value": dict_data["value"],
                        "data": dict_data["data"],
                        "index": dict_data["index"]
                    }],
                    "is_true": dict_data["is_true"],
                }

                # 临时存起来, 存到 all_cases 中
                all_cases.append(current_case)

            # id为None的情况, 一般就是步骤, 确保有当前用例数据的情况下, 把步骤添加进去
            elif current_case is not None:
                current_case["steps"].append({
                    "step_num": dict_data["step_num"],
                    "step_name": dict_data["step_name"],
                    "keyword": dict_data["keyword"],
                    "by": dict_data["by"],
                    "value": dict_data["value"],
                    "data": dict_data["data"],
                    "index": dict_data["index"]
                })

    # 过滤用例数据, 只保留is_true为True的用例
    data = [case for case in all_cases if case["is_true"]]

    # print(all_cases)
    # print(data)

    workbook.close()

    return data


# read_excel()
